package com.fzq.config;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);          // 把redis的连接赋值给redisTemplate

        redisTemplate.setKeySerializer(RedisSerializer.string());       // 设置Key的序列化方式， String方式
        redisTemplate.setValueSerializer(RedisSerializer.json());       // 设置Valude的序列化方式, json序列化
        redisTemplate.setHashKeySerializer(RedisSerializer.string());   // 设置Hash数据类型 域的序列化方式，String方式
        redisTemplate.setHashValueSerializer(RedisSerializer.json());   // 设置Hash数据类型 域值的序列化方式, json序列化

        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();     // 初始化redis缓存配置类
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()))  // 设置序列化key的方式， String方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));        // 设置序列化value的方式，json方式

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).build();       // 依据redis连接和配置 创建redis缓存管理对象
        return cacheManager;
    }
}
